﻿/*
    Parker for Kaixin001.com 

    Copyright (C) 2008, TurboZV, turbozv@gmail.com, http://www.turbozv.com/

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    *KEEP THIS HEADER INFORMATION*
*/

// by xzsong.seu@gmail.com, 2008-09-20
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Helper
{
    class SerializeHelper
    {
        public static void Serialize<T>(T instance)
        {
            Type type = typeof(T);
            using (FileStream fs = new FileStream(type.Name + ".txt", FileMode.OpenOrCreate))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(fs, instance);
            }
        }

        public static T Deserialize<T>(out bool bFromFile) where T : class, new()
        {
            bFromFile = false;
            Type type = typeof(T);
            if (File.Exists(type.Name + ".txt"))
            {
                try
                {
                    using (FileStream fs = new FileStream(type.Name + ".txt", FileMode.Open))
                    {
                        BinaryFormatter formatter = new BinaryFormatter();
                        T t = formatter.Deserialize(fs) as T;
                        if (t != null)
                        {
                            bFromFile = true;
                            return t;
                        }
                    }
                }
                catch
                {
                    return new T();
                }
            }
            return new T();
        }
    }
}
